//  Copyright (c) 2010 Mahesh Sharma,Matt MacDonald
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.

package org.prx.prp.controller;

import org.prx.prp.model.BillboardAPI;
import org.prx.prp.utility.DatabaseAdapter;
import org.prx.prp.utility.XMLParser;

import android.database.Cursor;
import android.util.Log;

public class SyncManager {
	public SyncManager() {
		createModelTables();
	}

	private void createModelTables() {

		DatabaseAdapter.createTable(BillboardAPI.STREAMS_MODEL_FIELDS,
				"streams");
		DatabaseAdapter.createTable(BillboardAPI.STREAM_URLS_MODEL_FIELDS,
				"stream_urls");
		DatabaseAdapter.createTable(BillboardAPI.SOURCES_MODEL_FIELDS,
				"sources");
		DatabaseAdapter.createTable(BillboardAPI.PROGRAMS_MODEL_FIELDS,
				"programs");
		DatabaseAdapter.createTable(BillboardAPI.SCHEDULES_MODEL_FIELDS,
				"schedules");
		DatabaseAdapter.createTable(BillboardAPI.PRODUCTIONS_MODEL_FIELDS,
				"productions");
		DatabaseAdapter.createTable(BillboardAPI.PROGRAMS_LISTS_MODEL_FIELDS,
				"program_lists");
		DatabaseAdapter.createTable(BillboardAPI.PROGRAM_LISTINGS_MODEL_FIELDS,
				"program_listings");
		DatabaseAdapter.createTable(BillboardAPI.STREAMS_LISTS_MODEL_FIELDS,
				"stream_lists");
		DatabaseAdapter.createTable(
				BillboardAPI.STREAM_LISTINGS_SOURCES_MODEL_FIELDS,
				"stream_listings");
		DatabaseAdapter.createTable(BillboardAPI.CATEGORIES_MODEL_FIELDS,
				"categories");
		DatabaseAdapter.createTable(BillboardAPI.CATEGORIZATIONS_MODEL_FIELDS,
				"categorizations");
		DatabaseAdapter.createTable(BillboardAPI.AD_CONSTANTS_MODEL_FIELDS,
				"ad_constants");
		try {
			DatabaseAdapter
					.createTable("CREATE TABLE IF NOT EXISTS FAVORITE_STATIONS (ID INTEGER PRIMARY KEY,POSITION);");
			DatabaseAdapter
					.createTable("CREATE TABLE IF NOT EXISTS FAVORITE_PROGRAMS (ID INTEGER PRIMARY KEY,POSITION);");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void syncModels() {
		syncModel(BillboardAPI.SOURCES_MODEL_FIELDS, "sources", "source");
		syncModel(BillboardAPI.STREAMS_MODEL_FIELDS, "streams", "stream");
		syncModel(BillboardAPI.PROGRAMS_MODEL_FIELDS, "programs", "program");
	//	syncModel(BillboardAPI.PRODUCTIONS_MODEL_FIELDS, "productions",
				//"production");
		syncModel(BillboardAPI.CATEGORIES_MODEL_FIELDS, "categories",
				"category");
		syncModel(BillboardAPI.CATEGORIZATIONS_MODEL_FIELDS, "categorizations",
				"categorization");
		// syncModel(BillboardAPI.AD_CONSTANTS_MODEL_FIELDS, "ad_constants",
		// "ad_constant");
		syncModel(BillboardAPI.PROGRAMS_LISTS_MODEL_FIELDS, "program_lists",
				"program_list");
		syncModel(BillboardAPI.PROGRAM_LISTINGS_MODEL_FIELDS,
				"program_listings", "program_listing");
		syncModel(BillboardAPI.STREAMS_LISTS_MODEL_FIELDS, "stream_lists",
				"stream_list");
		syncModel(BillboardAPI.STREAM_LISTINGS_SOURCES_MODEL_FIELDS,
				"stream_listings", "stream_listing");
	}

	private long getLastUpdateTime(String modelName) {
		Cursor c = DatabaseAdapter.executeQuery("select max(updated_at_in_utc_seconds) as updated_after from "+modelName, null);
		c.moveToFirst();
		//Log.d("PRPAND","Sync at"+c.getLong(c.getColumnIndex(("updated_after"))));
		long result = c.getLong(c.getColumnIndex(("updated_after")));
		c.close();
		return result;		
	}

	private void syncModel(String[] fieldNames, String modelName,
			String objectName) {
		long updated_after = getLastUpdateTime(modelName);
		String url = BillboardAPI.BILLBOARD_MODEL_URL + modelName
				+ "?format=xml";
		Log.d("PRPAND","Sync"+modelName);
		if (updated_after != -1)
			url = url + "&updated_after=" + updated_after;
		if (modelName.equals("streams")) {
			XMLParser.sync(modelName, objectName, fieldNames, "stream_urls",
					"stream_url", BillboardAPI.STREAM_URLS_MODEL_FIELDS, url);
			return;
		}
		//String response = HttpRetriever.getData(url);
		//Log.d("PRPAND", "Count us" + response);
		XMLParser.sync(modelName, objectName, url, fieldNames);
		return;
	}
}